//
//  ArchiveDataTest.m
//  ArchiveDemo
//
//  Created by shk on 14/12/3.
//  Copyright (c) 2014年 com.shk. All rights reserved.
//

#import "ArchiveDataTest.h"

@implementation ArchiveDataTest


- (void) archiveData{
    NSArray *array = @[@"abc", @"你好", @123];//数组里面虽然可以存放多种类型，但是建议存放单一类型
    NSString *homePath = NSHomeDirectory();
    NSString *savePath = [homePath stringByAppendingPathComponent:@"temp/oc-demo-archive-data.array"];
    BOOL success = [NSKeyedArchiver archiveRootObject:array toFile:savePath];//此种方法，一个对象需要占用一个文件
    if(success){
        NSLog(@"achrive success");
    }
}

- (void)unAchiveData{
    NSString *homePath = NSHomeDirectory();
    NSString *savePath = [homePath stringByAppendingPathComponent:@"temp/oc-demo-archive-data.array"];
    NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:savePath];
    NSLog(@"%@", array);
}

- (void) archiveMutabelData{
    NSString *homePath = NSHomeDirectory();
    NSString *savePath = [homePath stringByAppendingPathComponent:@"temp/oc-demo-archive-mutabledata.array"];
    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    NSArray *array = @[@"jace", @"tom"];
    [archiver encodeObject:array forKey:@"names"];
    [archiver encodeInt:100 forKey:@"age"];
    [archiver finishEncoding];
    
    BOOL success = [data writeToFile:savePath atomically:YES];
    if(success){
        NSLog(@"archive success");
    }
}

- (void) unArchiveMutabelData{
    NSString *homePath = NSHomeDirectory();
    NSString *savePath = [homePath stringByAppendingPathComponent:@"temp/oc-demo-archive-mutabledata.array"];
    NSMutableData *data = [NSData dataWithContentsOfFile:savePath];
    NSKeyedUnarchiver *unAchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    int age = [unAchiver decodeObjectForKey:@"age"];
    NSArray *names = [unAchiver decodeObjectForKey:@"names"];
    NSLog(@"age=%d，names=%@", age, names);
    
}





@end
